<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps :active="activeName - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form
        ref="addformref"
        :model="addform"
        label-width="80px"
        :rules="addrules"
        label-position="top"
      >
        <el-tabs
          :before-leave="tabchecked"
          tab-position="left"
          v-model="activeName"
          @tab-click="handleClick"
        >
          <!-- 基本参数 -->
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addform.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addform.goods_weight"
                type="number"
              ></el-input> </el-form-item
            ><el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addform.goods_number"
                type="number"
              ></el-input> </el-form-item
            ><el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addform.goods_price" type="number"></el-input>
            </el-form-item>
            <!-- 级联框 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                clearable
                v-model="addform.goods_cat"
                :options="list"
                :props="propsobj"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, i) in manylist"
              :key="i"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item2"
                  v-for="(item2, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlylist"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handlesuccess"
              :headers="headerobj"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addform.goods_introduce"> </quill-editor>
            <el-button type="primary" class="addbtn" @click="addok"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 预览图片的对话框 -->
      <el-dialog title="预览图片" :visible.sync="picDialogVisible" width="30%">
        <img :src="img" alt="" class="pic" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      // 步骤条绑定的数据
      // active: 0,
      // tabs标签页绑定的数据
      activeName: '',
      // 表单对象
      addform: {
        goods_name: '',
        goods_cat: [],
        goods_number: 0,
        goods_price: 0,
        goods_weight: 0,
        // 添加图片路径对象的数组
        pics: [],
        // 商品描述信息
        goods_introduce: '',
        attrs: []
      },
      // 验证规则
      addrules: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      // 后台数据
      list: [],

      // props配置项
      propsobj: {
        expandTrigger: 'hover',
        label: 'cat_name',
        children: 'children',
        value: 'cat_id'
      },
      // 动态属性数据列表
      manylist: [],
      // 静态参数数据列表
      onlylist: [],
      // 手动配置请求头
      headerobj: {
        Authorization: sessionStorage.getItem('token')
      },
      // 定义上传图片的完整路径
      img: '',
      // 默认预览图片对话框关闭
      picDialogVisible: false
    }
  },
  created() {
    this.getlist()
  },
  // mounted () {},
  computed: {},
  watch: {},
  methods: {
    // 定义获取数据列表
    async getlist() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      // 赋值data中定义的数据
      this.list = res.data
      // console.log(this.list);
    },
    // 点击tabs触发该函数
    async handleClick() {
      // console.log(this.activeName);
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.addform.goods_cat[2]}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) {
          return
        }
        this.manylist = res.data
        this.manylist.forEach(element => {
          element.attr_vals = element.attr_vals.split(' ')
        })
      }
      if (this.activeName === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.addform.goods_cat[2]}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) {
          return
        }
        this.onlylist = res.data
      }
    },
    // 级联框改变触发
    handleChange() {
      // console.log(this.addform.goods_cat);
      if (this.addform.goods_cat.length !== 3) {
        this.addform.goods_cat = []
        return this.$message.error('请选择三级分类！')
      }
    },
    // 切换tab栏触发该事件
    tabchecked(newtab, oldtab) {
      if (oldtab === 0 && this.addform.goods_cat.length !== 3) {
        return false
      }
    },
    // 移出图片触发
    handleRemove(res) {
      const i = this.addform.pics.findIndex(item => {
        item.pics == res.response.data.tmp_path
      })
      this.addform.pics.splice(i, 1)
    },
    // 预览视图触发
    handlePreview(res) {
      this.img = res.response.data.url
      this.picDialogVisible = true
    },
    // 上传成功时触发
    handlesuccess(res) {
      this.addform.pics.push({ pics: res.data.tmp_path })
    },
    // 点击提交
    async addok() {
      this.$refs.addformref.validate(e => {
        if (!e) {
          return this.$message.error('请填写必填项')
        }
      })
      this.manylist.forEach(item => {
        this.addform.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' ')
        })
      })
      this.onlylist.forEach(item => {
        this.addform.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        })
      })
      var newaddform = JSON.parse(JSON.stringify(this.addform))
      newaddform.goods_cat = newaddform.goods_cat.join(',')
      // 数据准备完毕可以发请求
      const { data: res } = await this.$http.post('goods', newaddform)
      if (res.meta.status !== 201) {
        return this.$message.error('添加失败！')
      }
      this.$message.success('添加成功！')
      this.$router.push('/goods')
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 20px;
}
.pic {
  width: 100%;
}
.quill-editor {
  height: 240px;
}
.addbtn {
  margin-top: 70px;
}
</style>
